package models;

import play.db.ebean.Model;
import play.db.ebean.Model.Finder;

import javax.persistence.*;

import com.avaje.ebean.Page;
import com.avaje.ebean.validation.NotNull;

@Entity
public class Tree extends Model{
	
	@Id
	public Long id;
	
	@ManyToOne
	@NotNull
	public Plot plot;
	
	@OneToOne
	@NotNull
	public Species species;
	
	@NotNull
	public Float diameterAtBreastHeight; //cm
	
	@NotNull
	public Float height;	//m
	
	@OneToOne
	@NotNull
	public Crown crown;
	
	@NotNull
	public Integer age;
	
	//Finder
	public static Finder<Long, Tree> find = new Finder<Long, Tree>(
			Long.class, Tree.class);
	
	public static Tree getTree(Tree tree) {
		return find.fetch("tree").where().idEq(tree.id).findUnique();
	}
	
    /**
     * Return a page of Tree
     *
     * @param page Page to display
     * @param pageSize Number of computers per page
     * @param sortBy Computer property used for sorting
     * @param order Sort order (either or asc or desc)
     * @param filter Filter applied on the name column
     */
    public static Page<Tree> page(int page, int pageSize, String sortBy, String order, String filter) {
        return 
            find.where()
                .ilike("name", "%" + filter + "%")
                .orderBy(sortBy + " " + order)
                .fetch("plot").fetch("species").fetch("crown")
                .findPagingList(pageSize)
                .getPage(page);
    }
    
    /*算法*/
    /*每棵数蓄积量
     * 
     */
    
    /*未完成
     * 
     */
    
	public Float volume(){
		//cubic meter
		Float volume = 0F;
		
		volume = (float) (this.species.a * Math.pow(this.diameterAtBreastHeight, this.species.b) * Math.pow(this.height, this.species.c));
		
		return volume;
	}
}
